package com.huawei.identify;
 
/**
 * @Author: liminghui
 * @Date: 2020/5/31 18:20
 * @Version:
 * @Description:
 */
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import com.huawei.identify.utils.FileUtil;
import com.huawei.identify.utils.HttpUtil;


import java.net.URLEncoder;
 
/**
 * 通用文字识别（高精度版）
 */
public class AccurateBasic {

    public static void main(String[] args) {
        String result = AccurateBasic.accurateBasic();

        JSONObject jsonObject = JSON.parseObject(result);
        JSONArray jsonArray = (JSONArray) jsonObject.get("words_result");
        for (Object o : jsonArray) {
            JSONObject jobj= (JSONObject) o;
            System.out.println(jobj.get("words"));
        }

    }
 
    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String accurateBasic() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        try {
            // 本地文件路径
            String filePath = "G:\\code\\java\\CrawlerSpider\\img\\1.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
 
            String param = "image=" + imgParam;
 
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String clientId = "GwATgzEgog4Ot2I91dv03GqK";
            // 官网获取的 Secret Key 更新为你注册的
            String clientSecret = "wHwO94IBqxUh4PM2BAQk1qqCTsmkeauD";
            String accessToken = AuthService.getAuth(clientId, clientSecret);
 
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 

}
